//
//  LSRequestManager.h
//  AFNetworkingDemo
//
//  Created by Leon on 16/2/2.
//  Copyright © 2016年 上海指旺信息科技有限公司. All rights reserved.
//

#import "LSRequestManager.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "NSString+Encryption.h"
#import <CommonCrypto/CommonDigest.h>
#import "AFNetworkActivityIndicatorManager.h"

#pragma mark - LSRequestManager


@interface LSRequestManager()

@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;

@end

@implementation LSRequestManager

- (AFHTTPSessionManager *)sessionManager {
    if(!_sessionManager) {
        _sessionManager = [AFHTTPSessionManager manager];
        _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html", @"text/plain",nil];
        [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    }
    return _sessionManager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static LSRequestManager *_manager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    return _manager;
}
/// 返回单例
+(instancetype)sharedInstance {
    return [[super alloc] init];
}

+ (void)getRequestWithURL:(NSString *)url
                   params:(NSDictionary *)params
                  success:(ReqSuccessBlock)successBlock
                  failure:(ReqFailureBlock)failBlock
                  showHUD:(BOOL)showHud {
    if (showHud) {
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    }
    
    [self setRequestHeader];
    [[LSRequestManager sharedInstance].sessionManager
     GET:[self dealWithUrl:url]
     parameters:params
     progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
         if (successBlock) {
#ifdef DEBUG
             [self printObject:responseObject];
#endif
             successBlock(responseObject);
         }
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
         if (failBlock) {
             failBlock(error);
         }
     }];
    
}

+ (void)getRequestWithURL:(NSString *)url
                   params:(NSDictionary *)params
                  success:(ReqSuccessBlock)successBlock
                  failure:(ReqFailureBlock)failBlock {
    [self getRequestWithURL:url
                     params:params
                    success:successBlock
                    failure:failBlock
                    showHUD:NO];
}
+ (void)putRequestWithURL:(NSString *)url
                   params:(NSDictionary *)params
                  success:(ReqSuccessBlock)successBlock
                  failure:(ReqFailureBlock)failBlock{
    [self putRequestWithURL:url
                     params:params
                    success:successBlock
                    failure:failBlock
                    showHUD:NO];
}
+ (void)putRequestWithURL:(NSString *)url
                   params:(NSDictionary *)params
                  success:(ReqSuccessBlock)successBlock
                  failure:(ReqFailureBlock)failBlock
                  showHUD:(BOOL)showHud{
    if (showHud) {
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    }
    
    [self setRequestHeader];
    [[LSRequestManager sharedInstance].sessionManager
     PUT:[self dealWithUrl:url]
     parameters:params
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
         if (successBlock) {
#ifdef DEBUG
             [self printObject:responseObject];
#endif
             successBlock(responseObject);
         }
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
         if (failBlock) {
             failBlock(error);
         }
     }];
    
}

+ (void)deleteRequestWithURL:(NSString *)url
                      params:(NSDictionary *)params
                     success:(ReqSuccessBlock)successBlock
                     failure:(ReqFailureBlock)failBlock
                     showHUD:(BOOL)showHud {
    if (showHud) {
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    }
    [self setRequestHeader];
    [[LSRequestManager sharedInstance].sessionManager DELETE:[self dealWithUrl:url] parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        if (successBlock) {
#ifdef DEBUG
            [self printObject:responseObject];
#endif
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        if (failBlock) {
            failBlock(error);
        }
    }];
}

+ (void)postRequestWithURL:(NSString *)url
                    params:(NSDictionary *)params
                   success:(ReqSuccessBlock)successBlock
                   failure:(ReqFailureBlock)failBlock
                   showHUD:(BOOL)showHud {
    if (showHud) {
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    }
    [self setRequestHeader];
    [[LSRequestManager sharedInstance].sessionManager
     POST:[self dealWithUrl:url]
     parameters:params
     progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
         if (successBlock) {
#ifdef DEBUG
             [self printObject:responseObject];
#endif
             successBlock(responseObject);
         }
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
         [MBProgressHUD showError:@"网络异常,请稍后重试!"];
         if (failBlock) {
             failBlock(error);
         }
     }];
    
}

+ (void)postRequestWithURL:(NSString *)url
                    params:(NSDictionary *)params
                   success:(ReqSuccessBlock)successBlock
                   failure:(ReqFailureBlock)failBlock {
    [self postRequestWithURL:url
                      params:params
                     success:successBlock
                     failure:failBlock
                     showHUD:NO];
}



+ (void)uploadFilesWithURL:(NSString *)url
                    params:(NSDictionary *)params
                     files:(NSArray *)files
                   success:(ReqSuccessBlock)successBlock
                   failure:(ReqFailureBlock)failBlock
                   showHUD:(BOOL)showHud {
    
    if (showHud) {
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    }
    [self setRequestHeader];
    [[LSRequestManager sharedInstance].sessionManager
     POST:url
     parameters:params
     constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull totalFormData) {
         for (UploadFormData *formData in files) {
             [totalFormData appendPartWithFileData:formData.data name:formData.name fileName:formData.filename mimeType:formData.mimeType];
         }
     }
     progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         if (showHud) {
             [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
         }
         if (successBlock) {
#ifdef DEBUG
             [self printObject:responseObject];
#endif
             successBlock(responseObject);
         }
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         if (showHud) {
             [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
             [MBProgressHUD showError:@"网络异常,请稍后重试!"];
         }
         if (failBlock) {
             failBlock(error);
         }
     }];
    
}

+ (void)uploadFilesWithURL:(NSString *)url
                    params:(NSDictionary *)params
                     files:(NSArray *)files
                   success:(ReqSuccessBlock)successBlock
                   failure:(ReqFailureBlock)failBlock {
    [self uploadFilesWithURL:url
                      params:params
                       files:files
                     success:successBlock
                     failure:failBlock
                     showHUD:NO];
    
}


+ (void)downloadFileWithURL:(NSURL *)url
                   filename:(NSString *)filname
                    success:(DownloadSuccessBlock)successBlock
                    failure:(ReqFailureBlock)failBlock
                    showHUD:(BOOL)showHud {
    [self createCacheFolder];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil] URLByAppendingPathComponent:@"SXT"];
        return [documentsDirectoryURL URLByAppendingPathComponent:filname];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error) {
            if (failBlock){
                failBlock(error);
            }
        } else  {
            if (successBlock) {
                successBlock(response, filePath);
            }
            DebugLog(@"file download to => %@", filePath);
        }
    }];
    
    [downloadTask resume];
    
}


+ (void)downloadFileWithURL:(NSURL *)url
                   filename:(NSString *)filname
                    success:(DownloadSuccessBlock)successBlock
                    failure:(ReqFailureBlock)failBlock{
    
    [self downloadFileWithURL:url
                     filename:filname
                      success:successBlock
                      failure:failBlock
                      showHUD:NO];
}

+ (void)downloadDataWithURL:(NSURL *)url
                    success:(ReqSuccessBlock)successBlock
                    failure:(ReqFailureBlock)failBlock {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"%@ %@", response, responseObject);
        }
    }];
    [dataTask resume];
}


+ (void)createCacheFolder {
    NSString *sxtPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"SXT"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:sxtPath isDirectory:&isDir];
    if (!(isDir && isDirExist)) {
        [fileManager createDirectoryAtPath:sxtPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
}


+ (NSString *)dealWithUrl:(NSString *)url {
    //url 处理操作
    if ([url hasPrefix:@"http"]) {
        
        return url;
    }
    return [NSString stringWithFormat:@"%@%@",BASE_URL,url];
}

+ (void)printObject:(NSDictionary *)responseObject{
    if ([NSJSONSerialization isValidJSONObject:responseObject]){
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"response --> %@",json);
    }
}

+ (void)setRequestHeader {
//    [UserDefaults setObject:@"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEwOSwiZXhwIjoxNTI5MDMzODUwfQ.P_nBxwAxpC_TatSjBsFHEftFupgi6pfAlV9C8V6TtFc" forKey:K_LOGININFO_TOKEN];
//    [UserDefaults synchronize];

    [[LSRequestManager sharedInstance].sessionManager.requestSerializer setValue:[UserDefaults objectForKey:K_LOGININFO_TOKEN] forHTTPHeaderField:@"token"];
    NSLog(@"token----->%@",[UserDefaults objectForKey:K_LOGININFO_TOKEN]);
}

@end


#pragma mark - UploadFordData
@implementation UploadFormData

- (NSString*)md5String:(NSString*)str {
    const char *cStr = [str UTF8String];
    unsigned char result[32];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    // 先转MD5，再转大写
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
    
}

- (NSString *)fileName {
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-mm-dd"];
    NSString *time = [NSString stringWithFormat:@"%@",[formatter stringFromDate:currentDate]];
    return [NSString stringWithFormat:@"%@.png",[self md5String:time]];
}

- (NSString *)mimeType {
    return @"image/png";
}

@end
